package com.sjgs.gis.web.rest;

import com.sjgs.gis.web.errors.BadRequestAlertException;
import com.sjgs.gis.service.PluginService;
import com.sjgs.gis.service.dto.PluginDTO;
import com.sjgs.gis.service.dto.PluginCriteria;
import com.sjgs.gis.service.PluginQueryService;

import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing {@link com.sjgs.gis.domain.Plugin}.
 */
@RestController
@RequestMapping("/api")
public class PluginResource {

    private final Logger log = LoggerFactory.getLogger(PluginResource.class);

    private static final String ENTITY_NAME = "geoserverportalPlugin";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final PluginService pluginService;

    private final PluginQueryService pluginQueryService;

    public PluginResource(PluginService pluginService, PluginQueryService pluginQueryService) {
        this.pluginService = pluginService;
        this.pluginQueryService = pluginQueryService;
    }

    /**
     * {@code POST  /plugins} : Create a new plugin.
     *
     * @param pluginDTO the pluginDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new pluginDTO, or with status {@code 400 (Bad Request)} if the plugin has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/plugins")
    public ResponseEntity<PluginDTO> createPlugin(@Valid @RequestBody PluginDTO pluginDTO) throws URISyntaxException {
        log.debug("REST request to save Plugin : {}", pluginDTO);
        if (pluginDTO.getId() != null) {
            throw new BadRequestAlertException("A new plugin cannot already have an ID", ENTITY_NAME, "idexists");
        }
        PluginDTO result = pluginService.save(pluginDTO);
        return ResponseEntity.created(new URI("/api/plugins/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /plugins} : Updates an existing plugin.
     *
     * @param pluginDTO the pluginDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated pluginDTO,
     * or with status {@code 400 (Bad Request)} if the pluginDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the pluginDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/plugins")
    public ResponseEntity<PluginDTO> updatePlugin(@Valid @RequestBody PluginDTO pluginDTO) throws URISyntaxException {
        log.debug("REST request to update Plugin : {}", pluginDTO);
        if (pluginDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        PluginDTO result = pluginService.save(pluginDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, pluginDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code GET  /plugins} : get all the plugins.
     *
     * @param pageable the pagination information.
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of plugins in body.
     */
    @GetMapping("/plugins")
    public ResponseEntity<List<PluginDTO>> getAllPlugins(PluginCriteria criteria, Pageable pageable) {
        log.debug("REST request to get Plugins by criteria: {}", criteria);
        Page<PluginDTO> page = pluginQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * {@code GET  /plugins/count} : count all the plugins.
     *
     * @param criteria the criteria which the requested entities should match.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
     */
    @GetMapping("/plugins/count")
    public ResponseEntity<Long> countPlugins(PluginCriteria criteria) {
        log.debug("REST request to count Plugins by criteria: {}", criteria);
        return ResponseEntity.ok().body(pluginQueryService.countByCriteria(criteria));
    }

    /**
     * {@code GET  /plugins/:id} : get the "id" plugin.
     *
     * @param id the id of the pluginDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the pluginDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/plugins/{id}")
    public ResponseEntity<PluginDTO> getPlugin(@PathVariable Long id) {
        log.debug("REST request to get Plugin : {}", id);
        Optional<PluginDTO> pluginDTO = pluginService.findOne(id);
        return ResponseUtil.wrapOrNotFound(pluginDTO);
    }

    /**
     * {@code DELETE  /plugins/:id} : delete the "id" plugin.
     *
     * @param id the id of the pluginDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/plugins/{id}")
    public ResponseEntity<Void> deletePlugin(@PathVariable Long id) {
        log.debug("REST request to delete Plugin : {}", id);
        pluginService.delete(id);
        return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();
    }
}
